<template>
  <el-card>
    <BreadCrumb />
    <el-form ref="FormRef" :rules="FormRules" :model="form" label-width="120px">
      <el-form-item
        prop="courseName"
        label="课程名称"
      >
        <el-input v-model="form.courseName" autocomplete="off" />
      </el-form-item>
      <el-form-item
        prop="experimentName"
        label="实验名称"
      >
        <el-input v-model="form.experimentName" autocomplete="off" />
      </el-form-item>
      <el-form-item
        label="班级名称"
        prop="className"
      >
        <el-cascader v-model="form.className" :options="cascaderOptions" :props="cascaderProps" />
      </el-form-item>
      <el-form-item
        prop="teacherId"
        label="老师工号"
      >
        <el-input v-model="form.teacherId" autocomplete="off" disabled />
      </el-form-item>
      <el-form-item
        prop="teacherName"
        label="授课老师"
      >
        <el-input v-model="form.teacherName" autocomplete="off" disabled />
      </el-form-item>
      <el-form-item class="form_button">
        <el-button type="primary" :disabled="btnDisabled" @click="saveOrUpdate()">
          {{ isAdd === true ? '添加' : '更新' }}
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import Cookies from 'js-cookie'
import BreadCrumb from '@/components/BreadCrumb'
import { isConfirm } from '@/utils/confirm'
import { getClassList } from '@/api/classApi'
import { getMajorList } from '@/api/majorApi'
import { addSchedule, getScheduleById, updateSchedule } from '@/api/scheduleApi'
import { getUserName } from '@/api/teacherApi'
export default {
  components: {
    BreadCrumb
  },
  data() {
    return {
      // 班级列表数据
      classList: [],
      // 专业班级级联选择器绑定数据
      cascaderOptions: [],
      // 级联选择器配置
      cascaderProps: { expandTrigger: 'hover', multiple: true, emitPath: false },
      // 表单
      form: {
        teacherName: '',
        courseName: '',
        className: [],
        experimentName: ''
      },
      FormRules: {
        courseName: [
          { required: true, message: '请输入课程名称', trigger: 'blur' }
        ],
        className: [
          { required: true, message: '请输入班级名称', trigger: 'blur' }
        ],
        experimentName: [
          { required: true, message: '请输入实验名称', trigger: 'blur' }
        ]
      },
      // 是否是添加排课信息操作
      isAdd: true,
      // 按钮是否禁用
      btnDisabled: true
    }
  },
  created() {
    // 获取班级专业级联选择器数据
    this.getCascaderOptions()
    // 初始化表单数据
    this.initForm()
    // 解禁按钮
    this.btnDisabled = false
  },
  methods: {
    // 根据当前路由初始化表单数据
    initForm() {
      // 判断当前是添加操作还是修改操作，根据路由判断
      if (this.$route.path.indexOf('/schedule/edit/') !== -1) {
        // 修改操作
        this.isAdd = false
        // 初始化修改表单
        this.editInitForm()
      } else {
        // 添加操作
        this.isAdd = true
        // 初始化添加表单
        this.addInitForm()
      }
    },
    // 初始化添加操作表单数据
    async addInitForm() {
      const params = this.$route.params
      this.form.semesterId = params.semesterId
      this.form.weekNum = Number(params.weekNum)
      this.form.week = Number(params.week)
      this.form.time = Number(params.time)
      this.form.teacherId = Cookies.get('teacherId')
      // 查询用户名
      const { data: res } = await getUserName()
      this.form.teacherName = res.username
    },
    // 初始化修改操作表单数据
    async editInitForm() {
      const params = this.$route.params
      // 根据 id 获取排课信息
      const { data: res } = await getScheduleById(params.scheduleId)
      this.form = res.schedule
      // 初始化 className 数据
      this.handleClassNameChangeToArray()
    },
    // 获取班级，专业数据，并将其一一对应，用作级联选择器的数据
    async getCascaderOptions() {
      // 获取专业数据
      const { data: res1 } = await getMajorList()
      // 获取班级数据
      const { data: res2 } = await getClassList()
      this.classList = res2.items
      res1.items.forEach(major => {
        const item = {
          value: major.sort,
          label: major.majorName
        }
        const childrenList = []
        res2.items.forEach(cl => {
          if (major.majorName === cl.majorName) {
            const children = {
              value: cl.id,
              label: cl.className
            }
            childrenList.push(children)
          }
        })
        item.children = childrenList
        this.cascaderOptions.push(item)
      })
    },
    // 点击表单按钮
    saveOrUpdate() {
      // 表单预校验
      this.$refs.FormRef.validate(async valid => {
        if (!valid) return
        // 判断是添加还是修改操作
        if (this.isAdd) this.addSchedule()
        else this.editSchedule()
      })
    },
    // 添加排课信息
    async addSchedule() {
      if (await isConfirm('提交后将无法修改，是否继续？')) {
        // 处理 className 数据
        this.handleClassNameChangeToString()
        await addSchedule(this.form)
        this.$message.success('添加成功')
        // 跳转至上一个路由
        this.$router.go(-1)
      }
    },
    // 修改排课信息
    async editSchedule() {
      if (await isConfirm('确认提交？')) {
        // 处理 className 数据
        this.handleClassNameChangeToString()
        await updateSchedule(this.form)
        this.$message.success('修改成功')
        // 跳转至上一个路由
        this.$router.go(-1)
      }
    },
    // 处理 className 数据，将数组转变为字符串
    handleClassNameChangeToString() {
      const className = []
      // 将存的 className 的 id 数组转换为班级名的字符串
      this.form.className.forEach(item1 => {
        // 遍历班级信息
        this.classList.forEach(item2 => {
          if (item1 === item2.id) className.push(item2.className)
        })
      })
      this.form.className = className.join(',')
    },
    // 处理 className 数据，将字符串转变为数组
    async handleClassNameChangeToArray() {
      // 将存的 className 的 班级名的字符串转换为 id 数组
      const className = []
      const classNameList = this.form.className.split(',')
      const { data: res2 } = await getClassList()
      const classList = res2.items
      classNameList.forEach(item1 => {
        // 遍历班级信息
        classList.forEach(item2 => {
          if (item1 === item2.className + '') className.push(item2.id)
        })
      })
      this.form.className = className
    }
  }
}
</script>

<style scoped>
.el-input {
  width: 400px;
}
.el-form-item {
  margin: 0 0 50px -30px;
}

</style>
